<template>
	<view class="custom_upload_wrap">
		<!-- 上传图片 -->
		<view class="upload_image" v-if="accept == 'image'">
			<view class="file_list" v-for="(item,index) in modelValue" :key="index">
				<image :src="item.url" class="image" @click="handlePreviewImage(index)"></image>
				<view class="close" @click="handleClose(index)" v-if="props.delete">
					<image src="/static/common/delete.png"></image>
				</view>
			</view>
			<view class="upload_icon" @click="handleUpload" v-if="modelValue.length < maxCount">
				<image src="/static/common/upload_add.png" mode="widthFix" v-if="!uploading"></image>
				<view class="uploading" v-if="uploading">
					<text>上传中...</text>
				</view>
			</view>
		</view>
		<!-- 上传视频 -->
		<view class="upload_video" v-if="accept == 'video'">
			<view class="file_list" v-for="(item,index) in modelValue" :key="index">
				<image :src="item.thumb" class="image" @click="handlePreviewVideo(index)" v-if="item.thumb"></image>
				<view class="default" @click="handlePreviewVideo(index)" v-else></view>
				<view class="close" @click="handleCloseVideo(index)" v-if="props.delete">
					<image src="/static/common/delete.png"></image>
				</view>
				<view class="play" @click="handlePreviewVideo(index)">
					<image src="/static/common/play.png" mode=""></image>
				</view>
			</view>
			<view class="upload_icon" @click="handleUploadVideo" v-if="modelValue.length < maxCount">
				<image src="/static/common/upload_add.png" mode="widthFix"></image>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref,defineComponent,defineProps,defineEmits } from 'vue';
	import commonApi from '@/api/common';

	defineComponent({
		name:'custom-upload'
	})
	
	const props = defineProps({
		modelValue: {
			type: Array,
			default:()=>{
				return []
			}
		},
		accept:{
			type:String,
			default:()=>{
				return 'image'
			}
		},
		delete:{
			type:Boolean,
			default:()=>{
				return true
			}
		},
		maxCount:{
			type:Number,
			default:()=>{
				return 9
			}
		}
	})
	
	
	// const fileList = ref([])
	const emit = defineEmits(['update:modelValue']);

	// 上传状态
	const uploading = ref(false);


	// 上传图片
	const handleUpload = async () => {
		if (uploading.value) {
			return;
		}

		try {
			// 计算剩余可上传数量
			const remainingCount = props.maxCount - props.modelValue.length;
			if (remainingCount <= 0) {
				uni.showToast({
					title: '已达到最大上传数量',
					icon: 'none'
				});
				return;
			}

			// 选择图片
			const chooseResult = await new Promise((resolve, reject) => {
				uni.chooseMedia({
					count: Math.min(remainingCount, 9),
					mediaType: ['image'],
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: resolve,
					fail: reject
				});
			});

			console.log('选择图片结果:', chooseResult);
			const { tempFiles } = chooseResult;

			if (!tempFiles || tempFiles.length === 0) {
				uni.showToast({
					title: '未选择图片',
					icon: 'none'
				});
				return;
			}

			uploading.value = true;
			const uploadedFiles = [];

			// 逐个上传文件
			for (let i = 0; i < tempFiles.length; i++) {
				const file = tempFiles[i];

				// 限制为10MB
				const maxSize = 10 * 1024 * 1024;
				if (file.size > maxSize) {
					uni.showToast({
						title: `第${i + 1}张图片大小不能超过10MB`,
						icon: 'none'
					});
					continue;
				}

				try {
	
					// 调用上传接口
					const uploadResult = await commonApi.upload(file.tempFilePath);

					console.log(`第${i + 1}张图片上传成功:`, uploadResult);

					// 添加到上传成功列表
					uploadedFiles.push({
						...file,
						url: uploadResult.url || uploadResult,
						uploaded: true
					});

				} catch (error) {
					console.error(`第${i + 1}张图片上传失败:`, error);

					let errorMessage = `第${i + 1}张图片上传失败`;
					if (error && error.message) {
						errorMessage = `第${i + 1}张图片: ${error.message}`;
					}

					uni.showToast({
						title: errorMessage,
						icon: 'none'
					});
				}
			}

			// 更新文件列表
			if (uploadedFiles.length > 0) {
				const newModelValue = [...props.modelValue, ...uploadedFiles];
				emit('update:modelValue', newModelValue);

				uni.showToast({
					title: `成功上传${uploadedFiles.length}张图片`,
					icon: 'success'
				});
			}

		} catch (error) {
			console.error('选择图片失败:', error);

			if (error.errMsg && error.errMsg.includes('cancel')) {
				// 用户取消选择
				return;
			}

			uni.showToast({
				title: '选择图片失败',
				icon: 'none'
			});

		} finally {
			uploading.value = false;
		}
	}
	// 删除图片
	const handleClose = (index)=>{
		// fileList.value.splice(index,1)
		props.modelValue.splice(index,1)
		emit('update:modelValue',props.modelValue)
	}
	// 预览图片
	const handlePreviewImage = (index)=>{
		uni.previewImage({
			current:index,
			// urls:fileList.value.map(item=>item.url)
			urls:props.modelValue.map(item=>item.url)
		})
	}
	
	
	/**
	 *  视频上传
	 */
	// 上传视频
	const handleUploadVideo = ()=>{
		uni.chooseVideo({
			success:async(res)=>{
				console.log(res)
				const { tempFilePath,thumbTempFilePath } = res
				// fileList.value.push({
				// 	tempFilePath,
				// 	thumbTempFilePath,
				// 	url:tempFilePath,
				// 	thumb:thumbTempFilePath,
				// 	type:'video'
				// })
				props.modelValue.push({
					tempFilePath,
					thumbTempFilePath,
					url:tempFilePath,
					thumb:thumbTempFilePath,
					type:'video'
				})
				emit('update:modelValue',props.modelValue)
			}
		})
	}
	// 删除视频
	const handleCloseVideo = (index)=>{
		// fileList.value.splice(index,1)
		props.modelValue.splice(index,1)
		emit('update:modelValue',props.modelValue)
	}
	// 预览视频
	const handlePreviewVideo = (index)=>{
		// #ifdef MP-WEIXIN
		wx.previewMedia({
			current:index,
			sources:props.modelValue
		})
		// #endif
	}
</script>

<style lang="scss">
	.custom_upload_wrap{
		.upload_image,.upload_video{
			display: flex;
			flex-wrap: wrap;
		}
		.file_list{
			width: 160rpx;
			height: 160rpx;
			margin-right: 20rpx;
			margin-bottom: 20rpx;
			position: relative;
			.image{
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
			}
			.default{
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
				background: black;
			}
			.close{
				width: 32rpx;
				height: 32rpx;
				position: absolute;
				top: -14rpx;
				right: -14rpx;
			}
			.play{
				width: 60rpx;
				height: 60rpx;
				position: absolute;
				top: 50%;
				left: 50%;
				margin-left: -30rpx;
				margin-top: -30rpx;
			}
		}
		.upload_icon{
			width: 160rpx;
			height: 160rpx;
			border-radius: 10rpx;
			border: 2rpx solid #CCCCCC;
			display: flex;
			align-items: center;
			justify-content: center;
			image{
				width: 42rpx;
				height: 42rpx;
			}
			.uploading {
				color: #999;
				font-size: 24rpx;
				text-align: center;
			}
		}
	}
</style>